/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.DccrDAO;
import com.cashmate.hibernate.pojo.Branches;
import com.cashmate.hibernate.pojo.Dccr;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.hibernate.pojo.Usertypes;
import com.cashmate.utilities.Utils;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Dine
 */
public class GridDccr extends ActionSupport {

    private static Logger logger = Logger.getLogger(GridDccr.class);
    private List<Dccr> gridModel;
    private Integer rows = 0;
    private Integer page = 0;
    private String sord;
    private String sidx;
    private String searchField;
    private String searchString;
    private String searchOper;
    private Integer total = 0;
    private Integer records = 0;
    private final DccrDAO dccrdao = (DccrDAO) ServletActionContext.getServletContext().getAttribute("dccrDAO");
    private final Branches b = (Branches) ServletActionContext.getRequest().getSession().getAttribute("branch");
    private final Usertypes ut = (Usertypes) ServletActionContext.getRequest().getSession().getAttribute("usertype");

    @Action(value = "/grid-dccr", results = {
        @Result(name = "success", type = "json")
    })
    @Override
    public String execute() throws Exception {
        try {
            //System.out.append(ClassUtils.toString(this)); 
            //max record
            int to = (rows * page);
            //offset record
            int from = to - rows;
            //instantiate a new criteria for a POJO class
            DetachedCriteria criteria = DetachedCriteria.forClass(Dccr.class);

            if (searchField != null && searchField.length() > 0) {
                try {
                    if (searchField.equals("dccrid") || searchField.equals("branchid")
                            || searchField.equals("numloan") || searchField.equals("daysleft")) {
                        criteria.add(Restrictions.eq(searchField, Integer.parseInt(searchString)));
                    } else if (searchField.equals("borrowercode")) {
                        String brRegex = Utils.segregate("letters", searchString);
                        criteria.add(Restrictions.like("branchcode", "%" + brRegex + "%"));
                        String numbers = Utils.segregate("numbers", searchString);
                        if (numbers != null && numbers.length() > 0) {
                            int boroRegex = Integer.parseInt(numbers);
                            criteria.add(Restrictions.like("borrowerid", boroRegex));
                        }
                    } else {
                        criteria.add(Restrictions.eq(searchField, Double.parseDouble(searchString)));
                    }
                } catch (NumberFormatException nfe) {
                    criteria.add(Restrictions.like(searchField, "%" + searchString + "%"));
                }
            }
            Object ses_dccrdate = ServletActionContext.getRequest().getSession().getAttribute("dccrdate");
            Object ses_branch = ServletActionContext.getRequest().getSession().getAttribute("dccrbranch");
            Object ses_dccrgendate = ServletActionContext.getRequest().getSession().getAttribute("dccrgendate");
            Object ses_genbranch = ServletActionContext.getRequest().getSession().getAttribute("dccrbranchname");
            //logger.info(ses_branch + " " + ses_dccrdate + " " + ses_dccrgendate + " " + ses_genbranch);
            if (ses_dccrgendate != null && ses_branch != null && ses_genbranch != null && ses_dccrdate != null) {
                criteria.add(Restrictions.eq("dategenerated", ses_dccrdate.toString()));
                criteria.add(Restrictions.eq("branchid", Integer.parseInt(ses_branch.toString())));
                criteria.add(Restrictions.eq("isactive", false));
            } else {
                if (b.getBranchid() != 1 && ut.getUsertypeid() != 1) {
                    criteria.add(Restrictions.eq("branchid", b.getBranchid()));
                }
                criteria.add(Restrictions.eq("isactive", true));
            }
            records = dccrdao.countByCriteria(criteria);
            criteria.setProjection(null);
            criteria.setResultTransformer(Criteria.ROOT_ENTITY);

            // handle Order By
            if (sidx != null && !sidx.equals("")) {
                if (sord.equals("asc")) {
                    criteria.addOrder(Order.asc(sidx));
                } else {
                    criteria.addOrder(Order.desc(sidx));
                }
            }

            criteria.addOrder(Order.desc("dategenerated"));
            criteria.addOrder(Order.asc("borrowername"));

            if (to > records) {
                to = records;
            }

            ServletActionContext.getRequest().getSession().setAttribute("dccr", dccrdao.findByCriteria(criteria));

            gridModel = dccrdao.findByCriteria(criteria, from, to);
            total = (int) Math.ceil((double) records / (double) rows);
            //logger.info(ClassUtils.toString(this));
        } catch (Exception ex) {
            Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
            if (emps != null) {
                logger.fatal("(" + emps.getIdnumber() + "):" + ex.getLocalizedMessage(), ex);
            } else {
                logger.fatal(ex.getLocalizedMessage(), ex);
            }
            ex.printStackTrace();
            addActionError(ex.getLocalizedMessage());
            return ERROR;
        } finally {
            DccrDAO.close();
        }
        return SUCCESS;
    }

    public List<Dccr> getGridModel() {
        return gridModel;
    }

    public void setGridModel(List<Dccr> gridModel) {
        this.gridModel = gridModel;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRecords() {
        return records;
    }

    public void setRecords(Integer records) {
        this.records = records;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

    public String getSearchField() {
        return searchField;
    }

    public void setSearchField(String searchField) {
        this.searchField = searchField;
    }

    public String getSearchOper() {
        return searchOper;
    }

    public void setSearchOper(String searchOper) {
        this.searchOper = searchOper;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public String getSidx() {
        return sidx;
    }

    public void setSidx(String sidx) {
        this.sidx = sidx;
    }

    public String getSord() {
        return sord;
    }

    public void setSord(String sord) {
        this.sord = sord;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }
}
